package com.myzhouye.biz.model;/***
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.*;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: game01
 * @description: 用户仓库实体类
 * @author: 那条蠢鱼
 * @create: 2025-11-11 16:49
 **/
@Data
@Entity
@Table(name = "user_warehouse")
public class UserWarehouseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; // 数据库自增ID

    @Column(nullable = false)
    private Long userId; // 所属用户ID

    @Column(nullable = false)
    private Integer capacity; // 总容量

    @Column(nullable = false)
    private Integer size; // 仓库个数

    @Column(columnDefinition = "JSON")
    private String itemsJson; // 物品存储(JSON格式)

    @Column(name = "created_at", updatable = false)
    private LocalDateTime createdAt = LocalDateTime.now(); // 创建时间

    @Column(name = "updated_at")
    private LocalDateTime updatedAt = LocalDateTime.now(); // 最后更新时间

    // 非持久化字段，用于运行时操作
    @Transient
    private Map<String, Integer> items = new HashMap<>();

    // 从JSON字符串加载items到Map
    @PostLoad
    public void loadItems() {
        if (itemsJson != null && !itemsJson.isEmpty()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                items = objectMapper.readValue(itemsJson, new TypeReference<Map<String, Integer>>() {});
            } catch (Exception e) {
                items = new HashMap<>();
            }
        }
    }

    // 将items Map转换为JSON字符串存储
    @PrePersist
    @PreUpdate
    public void saveItems() {
        this.updatedAt = LocalDateTime.now();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            itemsJson = objectMapper.writeValueAsString(items);
        } catch (Exception e) {
            itemsJson = "{}";
        }
    }

}
